package com.chilly.netty.action.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Created by Chilly Cui on 2021/1/12.
 */
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {

        //两个都是无限循环
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(); //线程组：处理连接请求
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();//线程组：处理和客户端的业务

        try {
            //创建服务端的启动对象，配置参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128) //设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });

            System.out.println("服务器 ready......");

            //绑定端口
            ChannelFuture cf = serverBootstrap.bind(6668).sync();

            //对通道的关闭动作进行监听，并且进行监听
            cf.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
